<template>
  <div class="common-wrap">
    <el-scrollbar>
      <div class="editor">
        <div class="editor-left">
          <editor
            api-key="your-tinymce-api-key"
            v-model="contents"
            licenseKey="gpl"
            :init="init"
          />
        </div>
        <el-scrollbar>
          <div class="editor-right">
            <el-table
              default-expand-all
              row-key="fieldCode"
              :tree-props="{ children: 'fieldList' }"
              :data="tableData"
              style="width: 100%; height: 600px"
            >
              <el-table-column prop="fieldName" label="参数" width="200" />
              <el-table-column prop="fieldCode" label="名称" width="200" />
              <el-table-column prop="type" label="类型" width="100" >
                <template #default="scope">
                  {{ scope.row.type === '1' ? 'String' : 'Array' }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="insertContentAndMaintainCursor(scope.row)"
                    >{{ $t("插入") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="padding: 0 10px">
              <div class="title">{{ $t("打印大小") }}</div>
              <div>
                <el-select
                  v-model="selectData.pageSizeType"
                  placeholder="Select"
                  size="small"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="flex-center text">
                <span>{{ $t("宽（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.pageWidth"
                  :disabled="selectData.value !== 'Custom'"
                  :min="1"
                  :max="99"
                  :precision="2"
                />
              </div>
              <div class="flex-center text">
                <span>{{ $t("高（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.pageHeight"
                  :disabled="selectData.value !== 'Custom'"
                  :min="1"
                  :max="99"
                  :precision="2"
                />
              </div>
              <div class="title">{{ $t("方向") }}</div>
              <div>
                <el-select
                  v-model="selectData.direction"
                  placeholder="Select"
                  size="small"
                >
                  <el-option
                    v-for="item in directionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="title">{{ $t("页边距") }}</div>
              <div class="flex-center text">
                <span>{{ $t("上（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.marginTop"
                  :min="0"
                  :max="99"
                  :precision="2"
                />
              </div>
              <div class="flex-center text">
                <span>{{ $t("下（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.marginBottom"
                  :min="0"
                  :max="99"
                  :precision="2"
                />
              </div>
              <div class="flex-center text">
                <span>{{ $t("左（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.marginLeft"
                  :min="0"
                  :max="99"
                  :precision="2"
                />
              </div>
              <div class="flex-center text">
                <span>{{ $t("右（CM）") }}： </span>
                <el-input-number
                  style="flex: 1"
                  v-model="selectData.marginRight"
                  :min="0"
                  :max="99"
                  :precision="2"
                />
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, computed } from "vue";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
import "tinymce/icons/default/icons";
import { ElMessage } from "element-plus";
const props = defineProps({
  content: {
    type: String,
    default: "",
  },
  tableData: {
    type: Array,
    default: () => [],
  },
  paperData: {
    type: Object,
    default: {
      value: "A4",
    },
  },
  batch: {
    type: String,
    default: "",
  },
});
const options = ref([
  {
    value: "A3",
    label: "A3",
  },
  {
    value: "A4",
    label: "A4",
  },
  {
    value: "A5",
    label: "A5",
  },
  {
    value: "B4",
    label: "B4",
  },
  {
    value: "B5",
    label: "B5",
  },
  {
    value: "Custom",
    label: "Custom",
  },
]);
const directionOptions = ref([
  {
    value: 1,
    label: "纵向",
  },
  {
    value: 0,
    label: "横向",
  },
]);
const emits = defineEmits(["update:content", "update:paperData"]);
const editorRef = ref(null);
const cursorPosition = ref([]);
const selectDom = ref(null);
// 监听元素选择变化
const handleElementSelection = (value) => {
  let node = editorRef.value.selection.getNode();
  // 过滤掉body和不需要处理的元素
  if (node.nodeName === "BODY" || node.nodeName === "HTML") {
    selectDom.value = null;
    return;
  }

  // 如果选中的是表格相关元素（th、td、tr），则获取其父级table标签
  const tableElements = ["TH", "TD", "TR", "THEAD", "TBODY", "TFOOT", "BR"];
  if (!value) return (selectDom.value = node);
  if (tableElements.includes(node.nodeName)) {
    let parent = node;
    // 向上查找table标签
    while (
      parent &&
      parent.nodeName !== "TABLE" &&
      parent.nodeName !== "HTML"
    ) {
      if (parent.parentNode.nodeName === value) {
        selectDom.value = parent.parentNode;
        break;
      }
    }
  }
};
const init = ref({
  // 设置语言为中文
  language_url: "/static/tinymce/langs/zh_CN.js",
  language: "zh_CN",
  // 确保编辑器可编辑
  readonly: false,
  // 禁用广告和版权信息
  promotion: false,
  branding: false,
  // 启用网格线
  visual: true,
  // 默认显示区块边框
  visualblocks_default_state: true,
  // 确保所有内容都在块级元素内
  forced_root_block: "div",
  setup: function (editor) {
    editorRef.value = editor;
    editor.on("init", function () {
      console.log("Editor initialized in editable mode");
      // 初始化时激活visualblocks插件
      editor.execCommand("visualBlocks");
      if (props.batch) {
        handleElementSelection();
        onAttribute(
          "data-th-each",
          `${props.batch}:${"${" + props.batch + "}"}`
        );
      }
    });
    editor.on("SelectionChange", () => {
      cursorPosition.value = editor.selection.getBookmark(2);
      // handleElementSelection();
    });
  },
  content_css: [
    "/static/tinymce/tinymce.css", // 你的自定义 CSS 文件路径
  ],
  plugins:
    "advlist anchor autolink charmap code fullscreen help image insertdatetime link lists media preview searchreplace table visualblocks wordcount",
  toolbar:
    "undo redo | styles | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | visualblocks",
  // 表格默认属性配置
  table_default_attributes: {
    class: "rq-table",
    border: "1",
  },
  height: "100%",
});
const contents = computed({
  set(val) {
    emits("update:content", val);
  },
  get() {
    return props.content;
  },
});
const selectData = computed({
  set(val) {
    emits("update:paperData", val);
  },
  get() {
    return props.paperData;
  },
});
watch(
  () => selectData.value.pageSizeType,
  (newVal, oldVal) => {
    if (newVal === "A3") {
      selectData.value.pageWidth = 29.7;
      selectData.value.pageHeight = 42.0;
    } else if (newVal === "A4") {
      selectData.value.pageWidth = 21.0;
      selectData.value.pageHeight = 29.7;
    } else if (newVal === "A5") {
      selectData.value.pageWidth = 14.8;
      selectData.value.pageHeight = 21.0;
    } else if (newVal === "B4") {
      selectData.value.pageWidth = 25.0;
      selectData.value.pageHeight = 35.3; 
    } else if (newVal === "B5") {
      selectData.value.pageWidth = 17.6;
      selectData.value.pageHeight = 25.0;
    }
  },
  { immediate: true }
);
const onAttribute = (value, data) => {
  editorRef.value.dom.setAttrib(selectDom.value, value, data);
};
const insertContentAndMaintainCursor = (row) => {
  if (row.type === "2") {
    handleElementSelection("TR");
    if (selectDom.value.nodeName === "TR") {
      let val = `${row.fieldCode}:${"${" + row.fieldCode + "}"}`
      if(props.batch){
        val = `${row.fieldCode}:${"${" + props.batch + "." + row.fieldCode + "}"}`
      }
      onAttribute(
        "data-th-each",
        val
      );
    } else {
      ElMessage.error("请选择表格");
    }
    return;
  } else if (row.type === "1") {
    handleElementSelection();
    if (selectDom.value.nodeName === "TD") {
      let val = "";
      if (row.parentFieldCode) {
        val = `${"${" + row.parentFieldCode + "." + row.fieldCode + "}"}`;
      } else if (props.batch) {
        val = `${"${" + props.batch + "." + row.fieldCode + "}"}`;
      } else {
        val = `${"${" + row.fieldCode + "}"}`;
      }
      const span = `<span class="mceNonEditable" data-th-text="${val}">${row.fieldCode}</span>`;
      editorRef.value.insertContent(span);
    } else {
      let val = `${"${" + row.fieldCode + "}"}`;
      if (props.batch) {
        val = `${"${" + props.batch + "." + row.fieldCode + "}"}`;
      }
      const span = `<span class="mceNonEditable" data-th-text="${val}">${row.fieldCode}</span>`;
      editorRef.value.insertContent(span);
    }
  }
  editorRef.value.nodeChanged();
  editorRef.value.selection.moveToBookmark(cursorPosition.value);
};
onMounted(() => {});
</script>

<style lang="scss" scoped>
.editor {
  display: flex;
  height: 100%;
}
.editor-left {
  flex: 1;
}
.editor-right {
  border: 2px solid #eee;
  margin-left: 20px;
  width: 400px;
}
.editor-right .title {
  margin: 15px 0 10px;
  font-size: 16px;
  font-weight: 600;
}
.editor-right .text {
  margin-top: 10px;
  font-size: 14px;
  color: #000;
}
.flex-center {
  display: flex;
  align-items: center;
}
</style>
